package com.bw.job;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bw.domain.AlipayConfig;
import com.bw.domain.BResult;
import com.bw.domain.OrderInfo;
import com.bw.service.OrderInfoService;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.checkerframework.checker.units.qual.A;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.client.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class MyJob {

    @Autowired
    OrderInfoService orderInfoService;

    @Autowired
    RedissonClient redissonClient;


    /**
     * 修改订单状态
     */
    @XxlJob("payStatusJob")
    public void  payStatusJob() throws AlipayApiException {


        //1. 查询所有未支付的订单

        List<OrderInfo> orderInfoList = orderInfoService.list(Wrappers.lambdaQuery(OrderInfo.class).eq(OrderInfo::getStatus, 0));

        for (OrderInfo orderInfo : orderInfoList) {

            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //设置请求参数
            AlipayTradeQueryRequest alipayRequest = new AlipayTradeQueryRequest();

            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = orderInfo.getOrderNo();
            //支付宝交易号
            String trade_no = "";
            //请二选一设置

            alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","+"\"trade_no\":\""+ trade_no +"\"}");

            //请求
            String result = alipayClient.execute(alipayRequest).getBody(); // 返回值是JSON格式不方便解析
            System.out.println("");

            // 如何 获取订单的状态
            AlipayTradeQueryResponse execute = alipayClient.execute(alipayRequest);
            String tradeStatus = execute.getTradeStatus(); // 订单状态

            if ("TRADE_SUCCESS".equals(tradeStatus)){
                String tradeNo = execute.getTradeNo(); // 支付宝订单号
                orderInfo.setStatus(1);  //修改订单状态为 已支付
                orderInfo.setAlipayNo(tradeNo);  // 修改支付宝的订单号
                orderInfoService.updateById(orderInfo);
            }

            // 如果状态还是0 --而且还超过10min --直接关闭订单状态改成3-----

        }




    }
    /**
     * 会定时执行这段代码
     */
    @XxlJob("test-job")
    public void  job(){

        System.out.println("----job--任务执行了----");

    }


    /**
     * 会定时执行这段代码
     */
    @XxlJob("test-job2")
    public void  job2(){

        System.out.println("---job2---任务执行了----");

    }
}
